package com.gitee.common.data.tree.node;

import com.gitee.common.data.tree.event.AddLeafTreeEvent;
import com.gitee.common.data.tree.event.DeleteLeafTreeEvent;
import com.gitee.common.data.tree.event.EventHandler;

import java.util.Set;

public abstract class OneFrontTreeItemNodeImpl extends AbstractTreeItemNode implements OneFrontTreeItemNodeI, AddLeafTreeEvent, DeleteLeafTreeEvent {

    private TreeItemNodeI front;

    @Override
    public int getFrontLength() {
        return front == null ? 0 : 1;
    }

    @Override
    public TreeItemNodeI getFront() {
        return front;
    }

    @Override
    public TreeItemNodeI changeFront(TreeItemNodeI newer) {
        TreeItemNodeI older = front;
        front = newer;
        return older;
    }

    @Override
    public TreeItemNodeI searchFront(String id) {
        if (front == null || id == null) {
            return null;
        }
        if (id.equals(front.getId())) {
            return front;
        }
        if (front instanceof FrontTreeItemNodeI) {
            return ((FrontTreeItemNodeI) front).searchFront(id);
        }
        return null;
    }

    @Override
    // AOP
    public void appendTo(TreeItemNodeI front) {
        this.fireAddLeafEvent(front, null);
        this.front = front;
    }

    @Override
    public void deleteFront(TreeItemNodeI node) {
        if (node != null && this.front != null && this.front.compareTo(node) == 0) {
            this.front = null;
        }
    }

    @Override
    public Object fireAddLeafEvent(TreeItemNodeI node, Object params) {
        Set<EventHandler> eventHandlers = this.getEventHandlers();
        for (EventHandler handler : eventHandlers) {
            handler.getType().equals("fireAddLeafEvent");
        }
        return null;
    }

    @Override
    public Object fireDeleteLeafEvent(TreeItemNodeI node, Object params) {
        return null;
    }
}
